# -*- coding: utf-8 -*-

import json
import logging
from odoo import http, fields
from odoo.http import request
from odoo.exceptions import UserError, ValidationError
from .api_base import APIBaseController

_logger = logging.getLogger(__name__)


class RoleController(APIBaseController):
    """角色管理控制器"""



    @http.route('/api/system/role/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def role_list(self, **kwargs):
        """角色列表查询"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:role:list'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs or {}
            
            # 构建查询条件
            domain = [('active', '=', True)]
            
            # 角色名称查询
            if data.get('roleName'):
                domain.append(('name', 'ilike', data['roleName']))
            
            # 角色编码查询
            if data.get('roleKey'):
                domain.append(('code', 'ilike', data['roleKey']))
            
            # 状态查询
            if 'status' in data:
                domain.append(('active', '=', data['status'] == '0'))
            
            # 时间范围查询
            if data.get('params', {}).get('beginTime'):
                domain.append(('create_time', '>=', data['params']['beginTime']))
            if data.get('params', {}).get('endTime'):
                domain.append(('create_time', '<=', data['params']['endTime']))
            
            # 分页参数
            page_num = data.get('pageNum', 1)
            page_size = data.get('pageSize', 10)
            offset = (page_num - 1) * page_size
            
            # 查询角色
            roles = request.env['device.user.role'].sudo().search(domain, offset=offset, limit=page_size, order='sequence, create_time desc')
            total = request.env['device.user.role'].sudo().search_count(domain)
            
            # 构建返回数据
            rows = []
            for role in roles:
                role_data = {
                    'roleId': role.id,
                    'roleName': role.name,
                    'roleKey': role.code,
                    'roleSort': role.sequence,
                    'dataScope': role.data_scope,
                    'menuCheckStrictly': True,
                    'deptCheckStrictly': True,
                    'status': '0' if role.active else '1',
                    'delFlag': '0',
                    'createTime': role.create_time and role.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'remark': role.description,
                    'admin': False
                }
                rows.append(role_data)
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': {
                    'total': total,
                    'rows': rows
                }
            }
            
        except Exception as e:
            _logger.error(f"查询角色列表异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}

    @http.route('/api/system/role', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def role_add(self, **kwargs):
        """新增角色"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:role:add'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            
            # 验证必填字段
            if not data.get('roleName'):
                return {'code': 500, 'msg': '角色名称不能为空', 'data': None}
            if not data.get('roleKey'):
                return {'code': 500, 'msg': '角色编码不能为空', 'data': None}
            
            # 检查角色编码是否已存在
            existing_role = request.env['device.user.role'].sudo().search([
                ('code', '=', data['roleKey'])
            ], limit=1)
            if existing_role:
                return {'code': 500, 'msg': '角色编码已存在', 'data': None}
            
            # 创建角色
            role_vals = {
                'name': data['roleName'],
                'code': data['roleKey'],
                'sequence': data.get('roleSort', 10),
                'description': data.get('remark'),
                'data_scope': data.get('dataScope', '1'),
                'create_by': current_user.id
            }
            
            new_role = request.env['device.user.role'].sudo().create(role_vals)
            
            # 分配权限
            if data.get('menuIds'):
                new_role.sudo().write({'permission_ids': [(6, 0, data['menuIds'])]})
            
            # 分配菜单权限
            if data.get('menuPermissionIds'):
                new_role.sudo().write({'menu_permission_ids': [(6, 0, data['menuPermissionIds'])]})
            
            # 分配部门权限（自定数据权限时）
            if data.get('dataScope') == '2' and data.get('deptIds'):
                new_role.sudo().write({'department_ids': [(6, 0, data['deptIds'])]})
            
            return {'code': 200, 'msg': '新增成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"新增角色异常: {str(e)}")
            return {'code': 500, 'msg': f'新增失败: {str(e)}', 'data': None}

    @http.route('/api/system/role/getInfo/<int:role_id>', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def get_info(self, role_id, **kwargs):
        current_user = self.verify_token()
        if not current_user:
            return {'code': 401, 'msg': '无效的访问令牌', 'data': None}

        # 检查权限
        if not self.check_permission('system:role:edit'):
            return {'code': 403, 'msg': '没有权限', 'data': None}
        role = request.env['device.user.role'].sudo().browse(role_id)
        role_data = {
            'roleId': role.id,
            'roleName': role.name,
            'roleKey': role.code,
            'roleSort': role.sequence,
            'dataScope': role.data_scope,
            'menuCheckStrictly': True,
            'deptCheckStrictly': True,
            'status': '0' if role.active else '1',
            'delFlag': '0',
            'createTime': role.create_time and role.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'remark': role.description,
            'admin': False
        }
        return {
            'code': 200,
            'msg': '查询成功',
            'data': role_data
        }

    @http.route('/api/system/role/<int:role_id>', type='json', auth='none', methods=['PUT'], csrf=False, cors='*')
    def role_edit(self, role_id, **kwargs):
        """修改角色"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:role:edit'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            
            # 查找角色
            role = request.env['device.user.role'].sudo().browse(role_id)
            if not role.exists():
                return {'code': 500, 'msg': '角色不存在', 'data': None}
            
            # 检查角色编码是否已被其他角色使用
            if data.get('roleKey') and data['roleKey'] != role.code:
                existing_role = request.env['device.user.role'].sudo().search([
                    ('code', '=', data['roleKey']),
                    ('id', '!=', role_id)
                ], limit=1)
                if existing_role:
                    return {'code': 500, 'msg': '角色编码已存在', 'data': None}
            
            # 更新角色信息
            role_vals = {
                'update_by': current_user.id
            }
            
            if data.get('roleName'):
                role_vals['name'] = data['roleName']
            if data.get('roleKey'):
                role_vals['code'] = data['roleKey']
            if 'roleSort' in data:
                role_vals['sequence'] = data['roleSort']
            if 'remark' in data:
                role_vals['description'] = data['remark']
            if data.get('dataScope'):
                role_vals['data_scope'] = data['dataScope']
            
            role.sudo().write(role_vals)
            
            # 更新权限
            if 'menuIds' in data:
                _logger.info(f"更新角色 {role_id} 的权限: {data['menuIds']}")
                role.sudo().write({'permission_ids': [(6, 0, data['menuIds'])]})
                _logger.info(f"权限更新成功，当前权限IDs: {role.permission_ids.ids}")
            
            # 更新菜单权限
            if 'menuPermissionIds' in data:
                _logger.info(f"更新角色 {role_id} 的菜单权限: {data['menuPermissionIds']}")
                role.sudo().write({'menu_permission_ids': [(6, 0, data['menuPermissionIds'])]})
                _logger.info(f"菜单权限更新成功，当前菜单权限IDs: {role.menu_permission_ids.ids}")
            
            # 更新部门权限
            if 'deptIds' in data:
                _logger.info(f"更新角色 {role_id} 的部门权限: {data['deptIds']}")
                role.sudo().write({'department_ids': [(6, 0, data['deptIds'])]})
                _logger.info(f"部门权限更新成功，当前部门权限IDs: {role.department_ids.ids}")
            
            return {'code': 200, 'msg': '修改成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"修改角色异常: {str(e)}")
            return {'code': 500, 'msg': f'修改失败: {str(e)}', 'data': None}

    @http.route('/api/system/role/<int:role_id>', type='json', auth='none', methods=['DELETE'], csrf=False, cors='*')
    def role_delete(self, role_id, **kwargs):
        """删除角色"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:role:remove'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            # 查找角色
            role = request.env['device.user.role'].sudo().browse(role_id)
            if not role.exists():
                return {'code': 500, 'msg': '角色不存在', 'data': None}
            
            # 检查是否有用户使用该角色
            user_assignments = request.env['device.user.role.assignment'].sudo().search([
                ('role_id', '=', role_id),
                ('active', '=', True)
            ])
            if user_assignments:
                return {'code': 500, 'msg': '该角色已分配给用户，不能删除', 'data': None}
            
            # 删除角色
            role.sudo().unlink()
            
            return {'code': 200, 'msg': '删除成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"删除角色异常: {str(e)}")
            return {'code': 500, 'msg': f'删除失败: {str(e)}', 'data': None}

    @http.route('/api/system/role/changeStatus', type='json', auth='none', methods=['PUT'], csrf=False, cors='*')
    def change_status(self, **kwargs):
        """修改角色状态"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:role:edit'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            role_id = data.get('roleId')
            status = data.get('status')
            
            if not role_id or status is None:
                return {'code': 500, 'msg': '参数错误', 'data': None}
            
            # 查找角色
            role = request.env['device.user.role'].sudo().browse(role_id)
            if not role.exists():
                return {'code': 500, 'msg': '角色不存在', 'data': None}
            
            # 修改状态
            role.sudo().write({
                'active': status == '0',
                'update_by': current_user.id
            })
            
            return {'code': 200, 'msg': '修改成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"修改角色状态异常: {str(e)}")
            return {'code': 500, 'msg': f'修改失败: {str(e)}', 'data': None}

    @http.route('/api/system/role/dataScope', type='json', auth='none', methods=['PUT'], csrf=False, cors='*')
    def data_scope(self, **kwargs):
        """修改角色数据权限"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:role:edit'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            role_id = data.get('roleId')
            data_scope = data.get('dataScope')
            
            if not role_id or not data_scope:
                return {'code': 500, 'msg': '参数错误', 'data': None}
            
            # 处理dataScope参数 - 如果是列表，取第一个值；如果是字符串，直接使用
            if isinstance(data_scope, list):
                if len(data_scope) == 0:
                    return {'code': 500, 'msg': 'dataScope不能为空', 'data': None}
                data_scope_value = str(data_scope[0])  # 取第一个值并转为字符串
            else:
                data_scope_value = str(data_scope)
            
            # 验证数据权限范围值是否有效
            # valid_scopes = ['1', '2', '3', '4', '5']
            # if data_scope_value not in valid_scopes:
            #     return {'code': 500, 'msg': '无效的数据权限范围', 'data': None}
            
            # 查找角色
            role = request.env['device.user.role'].sudo().browse(role_id)
            if not role.exists():
                return {'code': 500, 'msg': '角色不存在', 'data': None}
            
            # 更新数据权限
            role_vals = {
                'data_scope': data_scope_value,
                'update_by': current_user.username
            }
            
            # 自定数据权限时，更新部门权限
            if data_scope_value == '2' and data.get('deptIds'):
                role_vals['department_ids'] = [(6, 0, data['deptIds'])]
            elif data_scope_value != '2':
                role_vals['department_ids'] = [(5,)]  # 清空部门权限
            
            role.sudo().write(role_vals)
            
            return {'code': 200, 'msg': '修改成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"修改数据权限异常: {str(e)}")
            return {'code': 500, 'msg': f'修改失败: {str(e)}', 'data': None}

    @http.route('/api/system/role/permissions/<int:role_id>', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def get_role_permissions(self, role_id, **kwargs):
        """根据角色查询权限树"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:role:list'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            # 查找角色
            role = request.env['device.user.role'].sudo().browse(role_id)
            if not role.exists():
                return {'code': 500, 'msg': '角色不存在', 'data': None}
            
            # 获取所有权限
            all_permissions = request.env['device.permission'].sudo().search([
                ('status', '=', True)
            ], order='sequence, id')
            
            # 获取角色已分配的权限ID列表
            role_permission_ids = role.permission_ids.ids
            
            # 构建权限树
            def build_permission_tree(permissions, parent_id=None):
                tree = []
                for perm in permissions:
                    if perm.parent_id.id == parent_id if parent_id else not perm.parent_id:
                        children = build_permission_tree(permissions, perm.id)
                        
                        perm_data = {
                            'id': perm.id,
                            'label': perm.name,
                            'code': perm.code,
                            'type': perm.permission_type,
                            'parentId': perm.parent_id.id if perm.parent_id else None,
                            'path': perm.menu_path,
                            'component': perm.component,
                            'icon': perm.icon,
                            'perms': perm.perms,
                            'sequence': perm.sequence,
                            'visible': perm.visible,
                            'status': perm.status,
                            'checked': perm.id in role_permission_ids,  # 是否被选中
                            'children': children
                        }
                        
                        tree.append(perm_data)
                
                return tree
            
            permission_tree = build_permission_tree(all_permissions)
            # if current_user.is_admin :
            #     role_permission_ids = all_permissions.ids
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': {
                    'permissions': permission_tree,
                    'checkedKeys':  role_permission_ids,  # 已选中的权限ID列表
                    'roleInfo': {
                        'roleId': role.id,
                        'roleName': role.name,
                        'roleKey': role.code,
                        'dataScope': role.data_scope
                    }
                }
            }
            
        except Exception as e:
            _logger.error(f"查询角色权限树异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}

    @http.route('/api/system/permissions/tree', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def get_all_permissions_tree(self, **kwargs):
        """获取所有权限树（用于分配权限时的选择）"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:role:list'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            # 获取所有权限
            all_permissions = request.env['device.permission'].sudo().search([
                ('status', '=', True)
            ], order='sequence, id')
            
            # 构建权限树
            def build_permission_tree(permissions, parent_id=None):
                tree = []
                for perm in permissions:
                    if perm.parent_id.id == parent_id if parent_id else not perm.parent_id:
                        children = build_permission_tree(permissions, perm.id)
                        
                        perm_data = {
                            'id': perm.id,
                            'label': perm.name,
                            'code': perm.code,
                            'type': perm.permission_type,
                            'parentId': perm.parent_id.id if perm.parent_id else None,
                            'path': perm.menu_path,
                            'component': perm.component,
                            'icon': perm.icon,
                            'perms': perm.perms,
                            'sequence': perm.sequence,
                            'visible': perm.visible,
                            'status': perm.status,
                            'children': children
                        }
                        
                        tree.append(perm_data)
                
                return tree
            
            permission_tree = build_permission_tree(all_permissions)
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': permission_tree
            }
            
        except Exception as e:
            _logger.error(f"查询权限树异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}

    @http.route('/api/system/role/authUser/allocatedList', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def allocated_user_list(self, **kwargs):
        """查询角色已分配用户列表"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:role:list'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs or {}
            role_id = data.get('roleId')
            
            if not role_id:
                return {'code': 500, 'msg': '角色ID不能为空', 'data': None}
            
            # 构建查询条件
            domain = [
                ('role_assignment_ids.role_id', '=', role_id),
                ('role_assignment_ids.active', '=', True),
                ('del_flag', '=', '0')
            ]
            
            # 用户名查询
            if data.get('userName'):
                domain.append(('login', 'ilike', data['userName']))
            
            # 手机号查询
            if data.get('phonenumber'):
                domain.append('|')
                domain.append(('mobile', 'ilike', data['phonenumber']))
                domain.append(('phone', 'ilike', data['phonenumber']))
            
            # 分页参数
            page_num = data.get('pageNum', 1)
            page_size = data.get('pageSize', 10)
            offset = (page_num - 1) * page_size
            
            # 查询用户
            users = request.env['res.users'].sudo().search(domain, offset=offset, limit=page_size)
            total = request.env['res.users'].sudo().search_count(domain)
            
            # 构建返回数据
            rows = []
            for user in users:
                user_data = {
                    'userId': user.id,
                    'userName': user.login,
                    'nickName': user.nick_name or user.name,
                    'email': user.email,
                    'phonenumber': user.mobile or user.phone,
                    'status': user.status,
                    'createTime': user.create_time and user.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'dept': {
                        'deptName': user.department_id.name
                    } if user.department_id else None
                }
                rows.append(user_data)
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': {
                    'total': total,
                    'rows': rows
                }
            }
            
        except Exception as e:
            _logger.error(f"查询角色用户列表异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}
